package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.Dept;
import org.example.pojo.Result;
import org.example.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class DeptController {

//    public static final Logger log = LoggerFactory.getLogger(DeptController.class);

    @Autowired  //IOC容器注入Bean
    private DeptService deptService;

//    @RequestMapping(value = "depts",method = RequestMethod.GET)
    @GetMapping("depts")
    public Result list() {
        log.info("查询全部部门数据");
//        System.out.println("查询全部部门数据");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    /*
    * 删除部门
    * */
//    方式一：HttpServletRequest
//    @DeleteMapping("depts")
//    public Result delete(HttpServletRequest request) {
//        String idStr = request.getParameter("id");
//        Integer id = Integer.parseInt(idStr);
//        deptService.deleteById(id);
//        return Result.success();
//    }

//    - 方案二：通过Spring提供的 @RequestParam 注解，将请求参数绑定给方法形参
//    @DeleteMapping("depts")
//    public Result delete(@RequestParam("id") Integer id) {
//        deptService.deleteById(id);
//        return Result.success();
//    }

//    - 方案三：如果请求参数名与形参变量名相同，直接定义方法形参即可接收。（省略@RequestParam）
    @DeleteMapping("depts")
   public Result delete(Integer id) {
       deptService.deleteById(id);
       return Result.success();
   }


   /*
   * 添加部门，请求参数json
   * */
    @PostMapping("depts")
    public Result add(@RequestBody Dept dept) {
//        System.out.println("新增部门，dept = " + dept);
        log.info("新增部门，dept = " + dept);
        deptService.save(dept);
        return Result.success();
    }

    /*
    *  根据ID查询 - GET http://localhost:8080/depts/1
    * */
    @GetMapping("depts/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        Dept dept = deptService.findById(id);
        return Result.success(dept);
    }

    @PutMapping("depts")
    public Result update(@RequestBody Dept dept) {
//        System.out.println("修改部门，dept = " + dept);
        log.info("修改部门，dept = " + dept);
        deptService.update(dept);
        return Result.success();
    }

}
